/**
 * 发送验证码
 * @author 明浩
 */
import { useState } from "react";
import useSmsCode, { SmsCodeStatus } from "@/lib/hooks/use-sms-code";
import Taro from "@tarojs/taro";
import { Button } from "@nutui/nutui-react-taro";

export interface SmsCodeInputProps {
  style?: object;
  disabled?: boolean;
  onRequest: Function;
  phone: string;
}

const SmsCodeInput = (props: SmsCodeInputProps) => {
  const { onRequest } = props;
  const [loading, setLoading] = useState(false);
  const { smsCodeState, dispatch } = useSmsCode();
  const text =
    smsCodeState.status === SmsCodeStatus.default
      ? "获取验证码"
      : smsCodeState.status === SmsCodeStatus.startCountDown
      ? `${smsCodeState.count}s`
      : "重新获取验证码";

  const handleClick = async () => {
    if (!/^[1]{1}\d{10}$/.test(props.phone || "")) {
      Taro.showToast({
        title: "请输入正确手机号",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    if (
      ![SmsCodeStatus.default, SmsCodeStatus.endCountDown].includes(
        smsCodeState.status
      ) ||
      loading
    ) {
      return;
    }
    setLoading(true);
    try {
      await onRequest();
    } catch (error) {
      return;
      // const { data }: any = await geetestInitRegister();
      // const result = await new Promise<GeetestResult>((resolve) => {
      //   initGeetest(
      //     {
      //       gt: data.gt,
      //       challenge: data.challenge,
      //       offline: !data.success,
      //       // @ts-ignore
      //       new_captcha: data.new_captcha,
      //       product: 'bind',
      //     },
      //     (captchaObj) => {
      //       captchaObj
      //         .onReady(() => {
      //           // 验证码ready之后才能调用verify方法显示验证码
      //           captchaObj.verify();
      //         })
      //         .onSuccess(() => {
      //           const result = captchaObj.getValidate();
      //           resolve({
      //             geetestChallenge: result.geetest_challenge,
      //             geetestValidate: result.geetest_validate,
      //             geetestSeccode: result.geetest_seccode,
      //           });
      //         })
      //         .onError(() => {
      //           setLoading(false);
      //         })
      //         .onClose(() => {
      //           setLoading(false);
      //         });
      //     },
      //   );
      // });
      // await onRequest(result);
    } finally {
      setLoading(false);
    }
    dispatch({ type: "startCountDown" });
  };

  return (
    <Button
      disabled={props.disabled}
      style={{ ...props.style }}
      type="primary"
      size="small"
      onClick={handleClick}
    >
      {loading ? "发送中.." : text}
    </Button>
  );
};

export default SmsCodeInput;
